import { createRouter, createWebHashHistory } from 'vue-router'
import { useAuthStore } from '@/store/auth'

// 静态路由（保留 Home 为所有用户可见）
const staticRoutes = [
  { path: '/login', name: 'login', component: () => import('@/views/Login.vue') },
  {
    path: '/',
    name: 'layout',
    component: () => import('@/layout/DefaultLayout.vue'),
    redirect: '/home',
    meta: { requiresAuth: true },
    children: [
      { path: 'home', name: 'home', component: () => import('@/views/Home.vue'), meta: { title: '首页' } }
    ]
  }
]

const router = createRouter({
  history: createWebHashHistory(),
  routes: staticRoutes
})

// 自动扫描 views 下所有 vue 文件
const modules = import.meta.glob('@/views/**/*.vue')

// 动态组件解析器（返回懒加载函数）
function loadView(component) {
  const keys = Object.keys(modules)
  const matchKey = keys.find(key => key.includes(`/${component}.vue`))
  return matchKey ? modules[matchKey] : null
}

/**
 * 规范化动态路由
 * - 如果后端返回 component === 'Layout'，前端不再把它当作额外的 DefaultLayout 挂载，
 *   而是把它当作一个“带 children 的菜单容器”来处理（component 不赋值）。
 * - 保持 children 的相对路径（路由嵌套由 Router 控制），Sidebar 渲染时根据父路径拼 fullPath 显示。
 */
function normalizeDynamicRoute(route, parentName = '') {
  const name = parentName ? `${parentName}-${route.name}` : route.name
  const path = route.path // 不强制调整（保持后端约定，child 可能为 'role'，父为 '/system'）

  // Layout 类型：不要再挂载 DefaultLayout（避免重复），只保留 children
  if (route.component === 'Layout') {
    return {
      ...route,
      path,
      name,
      component: undefined,
      children: route.children?.map(child => normalizeDynamicRoute(child, name)) || []
    }
  }

  const newRoute = {
    ...route,
    path,
    name,
    meta: route.meta || {}
  }

  if (route.component) {
    const view = loadView(route.component)
    if (view) newRoute.component = view
  }

  if (route.children?.length) {
    newRoute.children = route.children.map(child => normalizeDynamicRoute(child, name))
  }

  return newRoute
}

// 动态添加路由（挂载到 'layout' 节点下）
export function addDynamicRoutes(dynamicRoutes) {
  dynamicRoutes.forEach(route => {
    const normalizedRoute = normalizeDynamicRoute(route)
    if (!normalizedRoute || !normalizedRoute.name) return

    if (!router.hasRoute(normalizedRoute.name)) {
      router.addRoute('layout', normalizedRoute) // 挂到 layout 下
    }
  })
}

// 路由守卫（恢复 Pinia、动态路由注入等）
router.beforeEach(async (to, from, next) => {
  const authStore = useAuthStore()

  // 恢复 Pinia 状态（如果存在）
  if (!authStore.accessToken && localStorage.getItem('auth-store')) {
    await authStore.$patch(JSON.parse(localStorage.getItem('auth-store')))
    if (authStore.accessToken && !authStore.userInfo) {
      await authStore.fetchUserInfo()
    }
  }

  const requiresAuth = to.matched.some(r => r.meta.requiresAuth)

  // 已登录访问 login -> 跳转首页
  if (authStore.isAuthenticated && to.path === '/login') {
    next({ path: '/' })
    return
  }

  // 受保护路由未登录 -> 跳 login
  if (requiresAuth && !authStore.isAuthenticated) {
    next({ path: '/login' })
    return
  }

  // 已登录且有动态路由需要添加
  if (authStore.isAuthenticated && authStore.routes?.length) {
    const firstDynamicRouteName = authStore.routes[0].name
    if (!router.hasRoute(firstDynamicRouteName)) {
      // 规范化并添加
      const routesToAdd = authStore.routes.map(r => normalizeDynamicRoute(r))
      routesToAdd.forEach(r => {
        if (r && r.name && !router.hasRoute(r.name)) router.addRoute('layout', r)
      })
      next({ ...to, replace: true })
      return
    }
  }

  next()
})

export default router
